﻿using System.Web;
using System.Text;
using System;
using System.Diagnostics;
namespace WebCumpleanios
{
    public class Utils
    {
        ///<summary>
        /// Base 64 Encoding with URL and Filename Safe Alphabet using UTF-8 character set.
        ///</summary>
        ///<param name="str">The origianl string</param>
        ///<returns>The Base64 encoded string</returns>
        public static string Base64Encode(string str)
        {
            byte[] encbuff = Encoding.UTF8.GetBytes(str);
            return HttpServerUtility.UrlTokenEncode(encbuff);
        }
        ///<summary>
        /// Decode Base64 encoded string with URL and Filename Safe Alphabet using UTF-8.
        ///</summary>
        ///<param name="str">Base64 code</param>
        ///<returns>The decoded string.</returns>
        public static string Base64Decode(string str)
        {
            byte[] decbuff = HttpServerUtility.UrlTokenDecode(str);
            return Encoding.UTF8.GetString(decbuff);
        }

        protected const string EventLogName = "WebPartCumpleanios";

        private static bool CheckSourceExists(string source)
        {
            if (EventLog.SourceExists(source))
            {
                EventLog evLog = new EventLog { Source = source };
                if (evLog.Log != EventLogName)
                {
                    EventLog.DeleteEventSource(source);
                }
            }

            if (!EventLog.SourceExists(source))
            {
                EventLog.CreateEventSource(source, EventLogName);
                EventLog.WriteEntry(source, String.Format("Event Log Created '{0}'/'{1}'", EventLogName, source), EventLogEntryType.Information);
            }

            return EventLog.SourceExists(source);
        }

        private static void WriteEventToMyLog(string source, string text, EventLogEntryType type)
        {
            if (CheckSourceExists(source))
            {
                EventLog.WriteEntry(source, text, type);
            }
        }

        public static void WriteEventLog(Exception ex) {
            WriteEventToMyLog(EventLogName, "Mensaje:\n"+ ex.Message + "\n Origen:\n" + ex.StackTrace, EventLogEntryType.Error);
        }
    }
}